
class Message {
    constructor() {
        this.init()
    }

    init() {
        //监听消息
        window.electron.ipcRenderer.on('on-sys-api-message', (_event, msg) => {
            // console.log('on-message-sys-api:', msg)
            //父页面发送消息
            window.parent.postMessage(msg,'*');
        });
    }

    // 发送消息
    sendMessage(msg) {
        let messageId = this.uuid();
        // console.log('messageId:', {...msg, messageId})
        window.electron.ipcRenderer.send("sys-api-message", {...msg, messageId})
        return messageId
    }

    // 接收消息
    receiveMessage(callback) {
        window.addEventListener('message',(msg)=>{
            callback(msg.data)
        },false);
    }

    uuid(len = 10) {
        let result = '';
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    
        for (var i = 0; i < len; i++) {
            result += characters.charAt(Math.floor(Math.random() * characters.length));
        }
    
        return result;
    }

    getMessageResult(opts){
        const { type, data, callback=()=>{} } = opts;

        let messageId=this.sendMessage({
            type: type,
            data: data
        });
        this.receiveMessage((msg)=>{
            if(msg.messageId==messageId){
                callback(msg.result)
            }
        })
    }

}
export default new Message()